import React, { useEffect, useState, useRef } from 'react';
import { Form, Input, Select, Button, message } from 'antd';
import { cloneDeep } from 'lodash';
import styled from 'styled-components';
import { dataSourceService } from '@/flowService';
import useFlowStore from '../../hooks/flowStore';
import CodeEditor from '@/components/codemirror/CodeEditor';

const { TextArea } = Input;

const FormContainer = styled.div`
  padding: 20px;
`;

const ButtonGroup = styled.div`
  margin-top: 24px;
  display: flex;
  gap: 8px;
`;

const MySqlForm = ({ data, onUpdate, onCancel }) => {
  const [form] = Form.useForm();
  const codeEditRef = useRef();
  const [dataSourceList, setDataSourceList] = useState([]);
  const [outputVariableList, setOutputVariableList] = useState([]);
  const flowContext = useFlowStore();

  const getDefaultData = () => ({
    key: '',
    name: '',
    desc: '',
    outgoings: [],
    incomings: [],
    elementType: 'MYSQL',
    dataSourceId: null,
    operationType: '',
    sql: '',
    variableKey: '',
  });

  const [nodeData, setNodeData] = useState(getDefaultData());

  useEffect(() => {
    if (data) {
      setNodeData(Object.assign(getDefaultData(), cloneDeep(data)));
    }
  }, [data]);

  useEffect(() => {
    const flowVariables = flowContext.data?.flowVariables || [];
    const variables = flowVariables
      .filter(item => item.envType !== 'INPUT')
      .map(item => ({ label: item.envName, value: item.envKey }));
    setOutputVariableList(variables);
  }, [flowContext.data]);

  const loadDataSourceData = async () => {
    const res = await dataSourceService.dataSourceList();
    if (res.success) {
      const list = res.result.map(item => ({
        label: item.dataSourceName,
        value: item.id
      }));
      setDataSourceList(list);
    }
  };

  useEffect(() => {
    loadDataSourceData();
  }, []);

  const validate = () => {
    if (!nodeData.name) {
      message.error('节点名称不能为空');
      return false;
    }
    if (!nodeData.dataSourceId) {
      message.error('数据源不能为空');
      return false;
    }
    if (!nodeData.operationType) {
      message.error('操作类型不能为空');
      return false;
    }
    return true;
  };

  const handleSubmit = () => {
    if (!validate()) {
      return;
    }
    onUpdate?.(cloneDeep(nodeData));
  };

  const handleCancel = () => {
    onCancel?.();
  };

  const handleValuesChange = (changedValues) => {
    setNodeData(prev => ({
      ...prev,
      ...changedValues
    }));
  };

  return (
    <FormContainer>
      <Form
        form={form}
        layout="vertical"
        initialValues={nodeData}
        onValuesChange={handleValuesChange}
      >
        <Form.Item label="节点编码">
          <span>{nodeData.key}</span>
        </Form.Item>

        <Form.Item
          label="节点名称"
          name="name"
          rules={[{ required: true, message: '请输入节点名称' }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item label="节点描述" name="desc">
          <TextArea placeholder="请输入" rows={2} />
        </Form.Item>

        <Form.Item
          label="数据源"
          name="dataSourceId"
          rules={[{ required: true, message: '请选择数据源' }]}
        >
          <Select placeholder="请选择数据源">
            {dataSourceList.map(item => (
              <Select.Option key={item.value} value={item.value}>
                {item.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="操作类型"
          name="operationType"
          rules={[{ required: true, message: '请选择操作类型' }]}
        >
          <Select placeholder="请选择操作类型">
            <Select.Option value="CHANGE">更改(增/删/改)</Select.Option>
            <Select.Option value="QUERY">查询</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item label="SQL语句" name="sql">
          <CodeEditor
            ref={codeEditRef}
            value={nodeData.sql}
            onChange={value => handleValuesChange({ sql: value })}
            width="480px"
            height="200px"
            lang="sql"
          />
        </Form.Item>

        {nodeData.operationType === 'QUERY' && (
          <Form.Item label="结果输出" name="variableKey">
            <Select placeholder="请选择变量">
              {outputVariableList.map(item => (
                <Select.Option key={item.value} value={item.value}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span>{item.value}</span>
                    <span style={{ color: 'var(--ant-text-color-secondary)', fontSize: '13px', marginLeft: '5px' }}>
                      {item.label}
                    </span>
                  </div>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        )}

        <ButtonGroup>
          <Button type="primary" onClick={handleSubmit}>
            确定
          </Button>
          <Button onClick={handleCancel}>
            取消
          </Button>
        </ButtonGroup>
      </Form>
    </FormContainer>
  );
};

export default MySqlForm; 